package test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/htm;charset=utf-8");//获取表单参数username


        String username = request.getParameter("username");
        System.out.println("username; "+username);
        if(!username.equalsIgnoreCase("zsf")) {
            response.getWriter().print("用户名或密码错误！");
        }   else   {
            HttpSession session = request.getSession();//获取session对象
            session.setAttribute("username", username);//在session中保存用户名

            //url重写时，使用重定向则重定向的url需用encodeRedirectURL重写url，而使用请求转发则较为简单，参看注释的请求转发
            String url=response.encodeRedirectURL("index1.jsp");
            response.sendRedirect(url);//重定向到index1.jsp
//            request.getRequestDispatcher("index1.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get");
    }
}
